package com.muh.exchange;

import com.muh.util.RabbitMQUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class HeadersConsumer {
    private static final String EXCHANGE_NAME = "headersExchange";
    private static final String QUEUE_NAME = "headersConsumer";
    public static void main(String[] args) throws IOException, TimeoutException {
        Map<String, Object> headersParams = new HashMap<>();
        headersParams.put("x-match", "all");//x-match:特定参数All表示全部匹配才算成功，any表示任意个匹配就是成功
        headersParams.put("one", "1");
        headersParams.put("two", "2");
        headersParams.put("three", "3");

        Connection connection = RabbitMQUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.HEADERS);//必须要是 headers 类型
        String queueName = channel.queueDeclare(QUEUE_NAME, true, false, false, null).getQueue();//临时对列
        String routingKey = "ourTestRoutingKey";
        channel.queueBind(queueName, EXCHANGE_NAME, routingKey, headersParams);//交换机绑定对列

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("---------------------------");
                System.out.println("routingKey: " + envelope.getRoutingKey());
                System.out.println("contentType: " + properties.getContentType());
                long deliveryTag = envelope.getDeliveryTag();
                System.out.println("deliveryTag: " + deliveryTag);
                System.out.println("content: " + new String(body, "UTF-8"));
//                channel.basicAck(deliveryTag, false);
                System.out.println("---------------------------");
            }
        };
        channel.basicConsume(queueName, true, consumer);//自动应答临时对列的名称
    }
}
